from flask import Flask, session, render_template, redirect, Blueprint, request
# 导入数据
from utils.getPageData import *
from utils.getPublicData import *

# 处理表单传入的图片文件
import uuid  # 生成通用唯一识别码
import os
from app import app
# 引入预测函数
from pred import index

# 获取随机数
import random

# 和app.py页面一致
pb = Blueprint('page', __name__, url_prefix='/page', template_folder='templates')

# 首页 -- /page/home
@pb.route('/home')
def home():
    # 获取登录时存储的用户名
    username = session.get('username')
    # 获取所有数据
    house_data = getAllHouse_info()
    # 获取地图数据 -- 格式为数组嵌套字典
    dataList = getHomeGeoChartData(house_data)
    # 获取数据标签数据
    totalLen, maxPrice, maxHouseType, maxHouseSale = getHomeTagsData(house_data)
    # 获取各城市房源个数数据
    radarOne, radarTwo = getHomeRadarData(house_data)
    # 获取地址词云图
    resSrc = getAddressData()
    # 获取预测表数据、预测总个数、预测价格的最大值、用户预测的最多城市、各城市数量占比
    historyList, dataLen, maxPredPrice, cityLenMax, cityPieData = getUserHistoryData(username)
    return render_template(
        'index.html',
        username=username,
        dataList=dataList,
        totalLen=totalLen,
        maxPrice=maxPrice,
        maxHouseType=maxHouseType,
        maxHouseSale=maxHouseSale,
        radarOne=radarOne,
        radarTwo=radarTwo,
        resSrc=resSrc,
        historyList=historyList,
        dataLen=dataLen,
        maxPredPrice=maxPredPrice,
        cityLenMax=cityLenMax,
        cityPieData=cityPieData,
    )


# 数据操作表页面
@pb.route('/tableData')
def tableData():
    # 获取登录时存储的用户名
    username = session.get('username')
    # 获取全部房屋数据
    house_data = getAllHouse_info()[-50:]
    return render_template(
        'tableData.html',
        username=username,
        house_data=house_data,
    )

# 详情页面 -- 由数据操作表-操作中的查看详情跳转
@pb.route('/detail')
def detail():
    # 获取登录时存储的用户名
    username = session.get('username')
    # 获取/page/detail?id=  中的id值
    id = request.args.get('id')
    house_info = getHouseInfoById(id)
    # print(house_info)
    return render_template(
        'detail.html',
        username=username,
        house_info=house_info,
    )

# 房屋添加页面 -- 添加房屋按钮
@pb.route('/addHouse', methods=['GET', 'POST'])
def addHouse():
    # 获取登录时存储的用户名
    username = session.get('username')
    if request.method == 'GET':
        return render_template(
            'addHouse.html',
            username=username,
        )
    else:
        # 获取表单传入的房源封面图片
        cover = request.files.get('cover')
        # 重新给图片命名
        coverFilename = str(uuid.uuid4()) + '.' + cover.filename.split('.')[-1]
        # 根目录下 - static目录下 - houseImage目录下 - 图片文件
        save_path = os.path.join(app.root_path, 'static', 'houseImage', coverFilename)
        # 图片存储
        cover.save(save_path)
        addHouseInfo({
            'title': request.form.get('title'),
            'city': request.form.get('city'),
            'region': request.form.get('region'),
            'address': request.form.get('address'),
            'rooms_desc': request.form.get('rooms_desc'),
            'area_range': request.form.get('area_range'),
            'price': request.form.get('price'),
            'houseDecoration': request.form.get('houseDecoration'),
            'company': request.form.get('company'),
            'houseType': request.form.get('houseType'),
            'tags': request.form.get('tags'),
            'cover': 'http://127.0.0.1:5000/static/houseImage/' + coverFilename
        })
        # return 'successful!!'
        return redirect('/page/tableData')

# 房屋数据修改页面 -- 由数据表格操作-修改操作跳转
@pb.route('/editHouse', methods=['GET', 'POST'])
def editHouse():
    # 获取登录时存储的用户名
    username = session.get('username')
    if request.method == 'GET':
        # 获取/page/editHouse?id=  中的id值
        id = request.args.get('id')
        house_info = getHouseInfoById(id)
        return render_template(
            'editHouse.html',
            username=username,
            house_info=house_info,
            id=id,
        )
    else:
        # 获取/page/editHouse?id=  中的id值
        id = request.args.get('id')
        # 获取表单传入的房源封面图片
        cover = request.files.get('cover')
        # 重新给图片命名
        coverFilename = str(uuid.uuid4()) + '.' + cover.filename.split('.')[-1]
        # 根目录下 - static目录下 - houseImage目录下 - 图片文件
        save_path = os.path.join(app.root_path, 'static', 'houseImage', coverFilename)
        # 图片存储
        cover.save(save_path)
        editHouseInfo({
            'title': request.form.get('title'),
            'city': request.form.get('city'),
            'region': request.form.get('region'),
            'address': request.form.get('address'),
            'rooms_desc': request.form.get('rooms_desc'),
            'area_range': request.form.get('area_range'),
            'price': request.form.get('price'),
            'houseDecoration': request.form.get('houseDecoration'),
            'company': request.form.get('company'),
            'houseType': request.form.get('houseType'),
            'tags': request.form.get('tags'),
            'cover': ('http://127.0.0.1:5000/static/houseImage/' + coverFilename) if request.files.get('cover') else '0'
        }, id)
        # return 'successful!!'
        return redirect('/page/tableData')

# 删除数据 -- 操作表格-删除
@pb.route('/delHouse')
def delHouse():
    # 获取/page/editHouse?id=  中的id值
    id = request.args.get('id')
    delHouseInfoById(id)
    return redirect('/page/tableData')

# 数据可视化 - 房屋价格分析
@pb.route('/priceCharts')
def priceCharts():
    # 获取登录时存储的用户名
    username = session.get('username')
    # 获取全部房屋数据
    house_data = getAllHouse_info()
    # 获取城市名
    citiesList = list(set([x.city for x in house_data]))
    # 获取选中的城市名
    defaultCity = request.args.get('defaultCity') if request.args.get('defaultCity') else citiesList[0]
    # 获取带有城市变量的全部房屋数据
    cityHouseData = getAllHouse_info(defaultCity)
    # 获取相关城市的价格信息 -- price
    priceBarX, priceBarY = getPriceChartBar(cityHouseData)
    # 获取开盘时间的城市房价均值 -- open_date & price
    priceLineX, priceLineY = getPriceChartLine(cityHouseData)
    # 获取城市总价数据 -- totalPrice_range
    totalData = getPriceChartScatter(cityHouseData)
    return render_template(
        'priceCharts.html',
        username=username,
        citiesList=citiesList,
        defaultCity=defaultCity,
        priceBarX=priceBarX,
        priceBarY=priceBarY,
        priceLineX=priceLineX,
        priceLineY=priceLineY,
        totalData=totalData
    )

# 房屋详情分析页面
@pb.route('/detailCharts')
def detailCharts():
    # 获取登录时存储的用户名
    username = session.get('username')
    # 获取全部房屋数据
    house_data = getAllHouse_info()
    # 获取矩形树图动态转换成旭日图的数据 -- 房型数据
    result = getDetailChartTreeSun(house_data)
    defaultType = request.args.get('type') if request.args.get('type') else 'small'
    # 获取饼图数据 -- 房屋建面
    x, y = getDetailChartPie(house_data, defaultType)
    return render_template(
        'detailCharts.html',
        username=username,
        result=result,
        x=x,
        y=y,
    )

# 房屋类型分析页面
@pb.route('/typeCharts')
def typeCharts():
    # 获取登录时存储的用户名
    username = session.get('username')
    # 获取全部房屋数据
    house_data = getAllHouse_info()
    # 获取城市名
    citiesList = list(set([x.city for x in house_data]))
    # 获取选中的城市名
    defaultCity = request.args.get('defaultCity') if request.args.get('defaultCity') else citiesList[0]
    # 获取带有城市变量的全部房屋数据
    cityHouseData = getAllHouse_info(defaultCity)
    # 获取房屋装修情况、房屋类型数据
    houseDecorationData, houseTypeData = getTypeChartsData(cityHouseData)
    return render_template(
        'typeCharts.html',
        username=username,
        citiesList=citiesList,
        defaultCity=defaultCity,
        houseDecorationData=houseDecorationData,
        houseTypeData=houseTypeData
    )

# 房屋其他分析页面
@pb.route('/otherCharts')
def otherCharts():
    # 获取登录时存储的用户名
    username = session.get('username')
    # 获取全部房屋数据
    house_data = getAllHouse_info()
    # 获取房屋交房情况数据
    zeroX, zeroY, hasDataY = getOtherChartsData(house_data)
    # 获取房屋售房情况数据
    resultData = getOtherChartsData_Pie(house_data)
    # 获取房屋标签数据
    tagsX, tagsY = getTagsData(house_data)
    return render_template(
        'otherCharts.html',
        username=username,
        zeroX=zeroX,
        zeroY=zeroY,
        hasDataY=hasDataY,
        resultData=resultData,
        tagsX=tagsX,
        tagsY=tagsY
    )

# 房屋公司词云图页面
@pb.route('/companyWc')
def companyWc():
    # 获取登录时存储的用户名
    username = session.get('username')
    return render_template(
        'companyWc.html',
        username=username
    )

# 房屋标签词云图页面
@pb.route('/tagsWc')
def tagsWc():
    # 获取登录时存储的用户名
    username = session.get('username')
    return render_template(
        'tagsWc.html',
        username=username
    )

# 房屋价格预测页面
@pb.route('/pricePred', methods=['GET', 'POST'])
def pricePred():
    # 获取登录时存储的用户名
    username = session.get('username')
    # 获取预测房价值
    priceResult = 0
    # 获取城市名
    citiesList = getCitiesList()
    if request.method == 'GET':
        return render_template(
            'pricePred.html',
            username=username,
            citiesList=citiesList,
            priceResult=priceResult,
        )
    else:
        # 售房情况
        statusRes = 1
        if request.form.get('sale_status') == '在售':
            statusRes = 1
        elif request.form.get('sale_status') == '已售':
            statusRes = 2
        elif request.form.get('sale_status') == '出租中':
            statusRes = 3
        elif request.form.get('sale_status') == '已出租':
            statusRes = 4
        elif request.form.get('sale_status') == '预售':
            statusRes = 5
        elif request.form.get('sale_status') == '其他':
            statusRes = 6
        # 模型
        model = index.model_train(index.getData())
        # 预测结果
        priceResult = index.pred(model, request.form.get('city'), int(request.form.get('rooms_desc')),
                                 int(request.form.get('area_range')), request.form.get('houseType'), statusRes)
        # 添加到History表中
        addHisotry(request.form.get('city'), priceResult, username)
        return render_template(
            'pricePred.html',
            username=username,
            citiesList=citiesList,
            priceResult=priceResult,
        )